<!--
*@Author: QWP
*@Description: 附件上传
*@Date: 2024-07-09 16:33:25
-->
<template>
  <u-dialog v-bind="$attrs"
    :width="$attrs['width'] || '45%'"
    :title="$attrs['title'] || '附件上传'"
    :maskClosable="false"
    destroyOnClose
    okText="上传"
    @submit="submit"
    @close="dialogClose">
    <a-upload-dragger
      v-model:fileList="fileList"
      name="file"
      :showUploadList="fileList.length != 0"
      :multiple="$attrs['multiple'] || true"
      :customRequest="customRequest"
      class="u-upload-custom-class"
      >
      <p class="ant-upload-drag-icon">
        <inbox-outlined></inbox-outlined>
      </p>
      <p class="ant-upload-text">可直接将文件拖拽到此处进行上传</p>
      <template #itemRender="{ file, actions }">
        <a-row class="f-w-100" style="height: auto">
          <div class="u-file-name">
            <div class="f-flex-row">
              <template v-if="getSuffix(file)">
                <div class="f-margin-r12">
                  <a-image :src="getSuffix(file)" width="25.64px" height="28px"></a-image>
                </div>
              </template>
              <span >{{ file.filename || file.name }} </span>
            </div>
            <CloseOutlined class="f-fr u-file-remove-icon" 
              style="line-height: 36px;"
              @click="deleteFile(file.uid)"/>
          </div>
        </a-row>
      </template>
    </a-upload-dragger>
  </u-dialog>
</template>

<script lang='ts' setup>
import { ref, reactive, computed, onMounted } from 'vue' 
import { useRoute, useRouter } from 'vue-router'
import { InboxOutlined } from '@ant-design/icons-vue';
import { nullC } from '@/util/common'
import { cloneDeep } from 'lodash'
import type { UploadProps } from 'ant-design-vue';
import * as fileApi from '@/service/file'
import { api } from '@/http/api'
import { urlFile } from '@/util/common';
defineOptions({
  name: 'u-upload'
})

interface Props {
  showDownload?: boolean,
  fileParams: object
}
const props = defineProps<Props>()

const emits = defineEmits(['submit']);

const fileList = ref<UploadProps['fileList']>([]);

// 删除
const deleteFile = (uid: string) => {
  fileList.value = fileList.value.filter(item => item.uid != uid)
}

// 自定义上传
const customRequest = (options) => {
  const { onSuccess, onError, file, onProgress } = options;
  let form = new FormData();
  form.append('storagetype', 'LOCAL')
  form.append('file', file)
  form.append('bucket', nullC(props.fileParams['bucket']))
  form.append('biztype', nullC(props.fileParams['biztype']))

  fileApi.upload(form, {
    onUploadProgress: ({ total, loaded }) => {
      const percent = (loaded / total) * 100;
      options.onProgress(
        { percent },  file
      );
    },
  })
  .then(res => {
    if(res.data.code == 0) {
      const data = cloneDeep(res.data.data || {})
      onSuccess(data, file)
    }
  })
  .catch(err => {
    onError(err)
  })
}

// 获取文件的后缀图标
const getSuffix = (file): string => {
  let suffixs = file.name.split('.');
  let suffix = (suffixs[suffixs.length - 1] || '').toLocaleLowerCase()
  const type = {
    'jpg': urlFile('knowledge/img.png'),
    'jpeg': urlFile('knowledge/img.png'),
    'png': urlFile('knowledge/img.png'),
    'gif': urlFile('knowledge/img.png'),
    "ppt": urlFile('knowledge/ppt.png'),
    "pptx": urlFile('knowledge/ppt.png'),
    "xls": urlFile('knowledge/excel.png'),
    "xlsx": urlFile('knowledge/excel.png'),
    "doc": urlFile('knowledge/word.png'),
    "docx": urlFile('knowledge/word.png'),
    "pdf": urlFile('knowledge/pdf.png'),
  }

  return type[suffix] || ''
}

// 提交保存
const submit = () => {
  let tFiles = fileList.value.filter(item => Object.values(item['response'] || {}).length > 0)
  let tFiles1 = tFiles.map(item => {
    let response = item.response || {}
    return { ...item, ...response, filename: nullC(response['originalfilename'])  }
  })
  dialogClose()
  emits('submit', tFiles1)
}

// 关闭
const dialogClose = () => {
  fileList.value = []
}

</script>

<style lang='scss'>
.u-upload-custom-class {
  .ant-upload {
    height: 200px;
    margin-bottom: 8px;
  }
  .ant-upload-list {
    min-height: 50px;
    height: auto;
    max-height: 260px;
    overflow: auto;
  }
  .u-file-name {
    position: relative;
    width: 100%; 
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    padding: 0 30px 0 8px;
    overflow: hidden; 
    white-space: nowrap; 
    text-overflow: ellipsis;
    font-family: PingFang SC, PingFang SC;
    font-weight: 400;
    font-size: 14px;
    color: #333333;
    &:first-child {
      margin-top: 8px;
    }
    &:hover {
      .u-file-remove-icon {
        display: block;
      }
    }
    .u-file-remove-icon {
      position: absolute;
      top: 50%;
      right: 10px;
      transform: translateY(-50%);
      display: none;
      cursor: pointer
    }
  }
}
</style>